package com.liujun.security.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liujun.security.entity.SysUser;
import com.liujun.security.mapper.SysUserMapper;
import com.liujun.security.server.UserService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.liujun.security.security.BCryptPasswordEncoder;

/**
 * @author pc
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService, UserService {

    private final SysUserMapper sysUserMapper;

    private final PasswordEncoder passwordEncoder;


    public UserDetailsServiceImpl(SysUserMapper sysUserMapper, BCryptPasswordEncoder passwordEncoder) {
        this.sysUserMapper = sysUserMapper;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    public SysUser loadUserByUsername(String s) throws UsernameNotFoundException {

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, s);

        SysUser sysUser = sysUserMapper.selectOne(wrapper);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        return sysUser;
    }

    @Override
    public Boolean save(SysUser sysUser) {


        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        int insert = sysUserMapper.insert(sysUser);

        if (insert == 1) {
            return true;
        }
        return false;
    }

    @Override
    public SysUser getUserById(int id) {

        SysUser sysUser = sysUserMapper.selectById(id);

        return sysUser;
    }
}
